<?php

namespace magein\think\utils\service;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Env;

class User
{

    /**
     * @return string|int|null
     */
    public function uuid()
    {
        $token = Auth::authorization();

        $decoded = $this->decode($token);

        return $decoded ? $decoded->user_id : null;
    }

    /**
     * @param $token
     * @return \stdClass
     */
    public function decode($token): ?\stdClass
    {
        try {
            $data = JWT::decode($token, new Key(Env::get('jwt.key'), 'HS256'));
        } catch (\Exception $exception) {
            $data = null;
        }
        return $data;
    }

    /**
     * @param $token
     * @return bool
     */
    public function check($token): bool
    {
        $data = $this->decode($token);

        if (empty($data)) {
            return false;
        }

        $user_id = $data->user_id;
        $exp = $data->exp;

        if (empty($user_id)) {
            return false;
        }

        if ($exp < time()) {
            return false;
        }

        return true;
    }

    /**
     * @param $user
     * @param int|null $expire_time
     * @return string
     */
    public function token($user, int $expire_time = null): string
    {
        if (is_array($user) || is_object($user)) {
            $id = $user['id'];
        } else {
            $id = $user;
        }

        $expire_time = $expire_time ?: Env::get('jwt.expire_time');

        if (empty($expire_time) || $expire_time <= 0) {
            $expire_time = 86400;
        }

        $payload = [
            'iss' => Env::get('jwt.iss', ''),
            'iat' => time(),
            'jti' => uniqid(),
            'exp' => time() + $expire_time,
            'user_id' => $id,
        ];

        return JWT::encode($payload, Env::get('jwt.key'), 'HS256');
    }
}

